using System.Diagnostics;
using System.Reflection;
using System.Threading;
using OpenTK.Windowing.GraphicsLibraryFramework;

namespace OpenTK.Windowing.Desktop
{
	public static class GLFWProvider
	{
		private static readonly GLFWCallbacks.ErrorCallback ErrorCallback = delegate(ErrorCode errorCode, string description)
		{
			throw new GLFWException(description, errorCode);
		};

		private static Thread _mainThread;

		private static bool Initialized = false;

		public static bool IsOnMainThread
		{
			get
			{
				if (CheckForMainThread)
				{
					return _mainThread == Thread.CurrentThread;
				}
				return true;
			}
		}

		public static bool CheckForMainThread { get; set; } = true;


		public static void EnsureInitialized()
		{
			if (CheckForMainThread)
			{
				if (_mainThread == null && !Thread.CurrentThread.IsBackground && !Thread.CurrentThread.IsThreadPoolThread && Thread.CurrentThread.IsAlive)
				{
					MethodInfo entryPoint = Assembly.GetEntryAssembly()!.EntryPoint;
					StackFrame[] frames = new StackTrace().GetFrames();
					for (int num = frames.Length - 1; num >= 0; num--)
					{
						MethodBase method = frames[num].GetMethod();
						if (entryPoint == method)
						{
							_mainThread = Thread.CurrentThread;
							break;
						}
					}
				}
				if (_mainThread?.ManagedThreadId != Thread.CurrentThread.ManagedThreadId)
				{
					throw new GLFWException("GLFW can only be called from the main thread!");
				}
			}
			if (!Initialized)
			{
				GLFW.Init();
				GLFW.SetErrorCallback(ErrorCallback);
				Initialized = true;
			}
		}
	}
}
